#include "Framework.h"

// calculate current "Frames Per Second"-rate
void RenderCalculateFPS()
{
  // 1000 milliseconds = 1 second
  static const fp32 oneSecond = 1000.0f;

  static ui64 now = 0,       // the current time
              timestamp = 0; // the next fps re-calculation timestamp

  static fp32 frames = 0.0f; // frames rendered

  // --------------------------------------------------------------------------

  now = TimeMs();       // get current time

  if (now >= timestamp) // every second, update the framerate
  {
    /* calculate the passed time:
       one second + amount of mSec difference timestamp->now */
    fp32 passedTime = oneSecond + (fp32)(now - timestamp);

    // calculate framerate
    fp32 currentFPS = (frames / passedTime) * oneSecond;

    frames = 0.0f;                     // reset counter
    timestamp = now + (ui64)oneSecond; // update next re-calculation timestamp

    // create new window title string to display calculated FPS
    STRING_GEN("[FPS: %.2f]\n", currentFPS);

    // set new window title
    WindowSetTitle(stringGen);
  }
  frames++; // add up rendered frame counter
};

// setup rasterization platform
void RenderInit()
{
};

// setup viewport
void RenderViewport(ui32 width, ui32 height)
{
  // limit size to min 1 pixel width/height
  CLAMP_LOW(width, 1);
  CLAMP_LOW(height, 1);

#ifdef OPENGL
  // setup viewport parameters
  glViewport(0, 0, (GLsizei)width, (GLsizei)height);
#endif
};

// setup camera parameters
void RenderSetCamera()
{
  static bool doThisOnce = false;
  if (doThisOnce == true) return;
  doThisOnce = true;
  // TODO: proper camera has to be used here!!!

#ifdef OPENGL
  // switch to projection matrix mode and load Identity
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  // create a perspective view
  gluPerspective(25.0f, 16.0f/9.0f, 0.1f, 1000.0f);

  // switch to view matrix mode and load Identity
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
#endif // OPENGL
};

// clear screen
void RenderClear()
{
#ifdef OPENGL
   // clear all buffers in the rasterization pipeline
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
#endif
};

// swap back-/frontbuffer
void RenderFlush()
{
#ifdef OPENGL
  glFlush(); // flush OpenGL pipeline processing
#endif // OPENGL
};
